<!-- LineChart.vue -->
<template>
  <div v-loading="loading" class="chart-container">
    <div v-if="error" class="error-tip">数据格式错误</div>
    <div v-else ref="chartEl" style="width: 700px; height: 400px"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

const props = defineProps({
  type: {
    type: String,
    required: true,
    validator: val => ['点赞', '收藏', '评论', '浏览'].includes(val)
  },
  days: {
    type: Number,
    default: 7,
    validator: val => val > 0 && val <= 30
  },
  data: {
    type: Array,
    required: true,
    validator: arr => arr.every(n => typeof n === 'number')
  }
})

const chartEl = ref(null)
const chartInstance = ref(null)
const loading = ref(true)
const error = ref(false)

// 生成日期标签
const generateDates = () => {
  return Array.from({ length: props.days }, (_, i) => {
    const diff = props.days - 1 - i
    return dayjs().subtract(diff, 'day').format('YYYY-MM-DD')
  })
}

// 初始化图表
const initChart = () => {
  if (!chartEl.value) return

  try {
    // 销毁旧实例
    if (chartInstance.value) {
      chartInstance.value.dispose()
    }

    // 数据校验
    if (props.data.length !== props.days) {
      throw new Error('数据长度与天数不符')
    }

    // 初始化图表
    chartInstance.value = echarts.init(chartEl.value)

    const option = {
      title: {
        text: `最近${props.days}天${props.type}趋势`,
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#333'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          const date = dayjs(params[0].name).format('M月D日')
          return `${date}<br/>${props.type}数：${params[0].value}`
        },
        // 强制显示配置
        alwaysShowContent: true,
        backgroundColor: 'red' // 测试用明显背景色
      },
      xAxis: {
        type: 'category',
        data: generateDates(),
        axisLabel: {
          formatter: value => dayjs(value).format('MM-DD')
        }
      },
      yAxis: {
        type: 'value',
        name: `${props.type}数`
      },
      series: [{
        data: props.data,
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.4
        },
        itemStyle: {
          color: getChartColor()
        }
      }]
    }

    chartInstance.value.setOption(option)
    error.value = false
  } catch (e) {
    console.error('图表初始化失败:', e)
    error.value = true
  } finally {
    loading.value = false
  }
}

// 根据类型获取颜色
const getChartColor = () => {
  const colors = {
    '点赞': '#1890ff',
    '收藏': '#52c41a',
    '评论': '#faad14',
    '浏览': '#f5222d'
  }
  return colors[props.type] || '#1890ff'
}

// 窗口变化自适应
const handleResize = () => {
  chartInstance.value?.resize()
}

// 生命周期
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.value?.dispose()
})

// 监听参数变化
watch([() => props.days, () => props.data], () => {
  loading.value = true
  initChart()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  position: relative;
}

.error-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ff4d4f;
}

</style>
